import { FC, Fragment, SyntheticEvent, useEffect, useState } from "react";
import { TabContext, TabList, TabPanel } from "@mui/lab";
import Box from "@mui/material/Box";
import { Tab } from "@mui/material";
import { useAPI } from "../../hooks/useAPI.ts";
import { styled } from "@mui/material/styles";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import TableFooter from "@mui/material/TableFooter";
import TablePagination from "@mui/material/TablePagination";
import Collapse from "@mui/material/Collapse";
import IconButton from "@mui/material/IconButton";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import { DatePicker, Form, Tag } from "@arco-design/web-react";
import dayjs from "dayjs";
import { SystemUserInfoData } from "../../api/types/system-user-info.ts";
import { ActivityListAndRecord } from "./ActivityListAndRecord.tsx";
import { css } from "@emotion/css";
import { ActivityChart } from "./ActivityChart.tsx";

// Function to generate the hour range string (e.g., "00:00-01:00")
function formatTimeRange(dateString: string) {
  // Extract the date and hour parts
  const [, hour] = dateString.split(" ");
  if (hour) {
    // Convert the hour to integers and calculate the next hour
    const startHour = parseInt(hour, 10);
    const endHour = startHour + 1;

    // Format the hours into HH:MM format
    const startTime = `${startHour.toString().padStart(2, "0")}:00`;
    const endTime = `${endHour.toString().padStart(2, "0")}:00`;

    return `${startTime} - ${endTime}`;
  }
  return dateString;
}
// Disable future dates
export const disableFutureDates = (current: any) => {
  return current.isAfter(dayjs().subtract(0, "day"), "day");
};

export function createData(
  index: number,
  time: string,
  status: string,
  residents: number,
  guests: number,
  danger: any
) {
  return { index, time, status, residents, guests, danger };
}

const StyledTableCell = styled(TableCell)(({ theme }) => ({
  [`&.${tableCellClasses.head}`]: {
    backgroundColor: "rgba(240, 240, 240, 1)",
    color: theme.palette.common.black,
    fontWeight: 600,
  },
  [`&.${tableCellClasses.body}`]: {
    fontSize: 14,
    backgroundColor: "rgba(255, 255, 255, 1)",
  },
}));

const DangerTableCell = styled(TableCell)(({ theme }) => ({
  [`&.${tableCellClasses.body}`]: {
    fontSize: 14,
    backgroundColor: "#FF9900",
    color: theme.palette.common.white,
  },
}));

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  "&:nth-of-type(odd)": {
    backgroundColor: theme.palette.action.hover,
  },
  // hide last border
  "&:last-child td, &:last-child th": {
    border: 0,
  },
}));

function Row(props: { row: ReturnType<typeof createData> }) {
  const { row } = props;
  const [open, setOpen] = useState(false);

  return (
    <Fragment>
      <StyledTableRow
        key={row.time}
        sx={{ "& > *": { borderBottom: "unset" } }}
      >
        <StyledTableCell
          align="center"
          component="th"
          scope="row"
          sx={{ maxWidth: "5px" }}
        >
          {row.danger.length > 0 ? (
            <IconButton
              aria-label="expand row"
              size="small"
              onClick={() => setOpen(!open)}
            >
              {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
            </IconButton>
          ) : null}
        </StyledTableCell>
        <StyledTableCell align="center">{row.index}</StyledTableCell>
        <StyledTableCell align="center">
          {formatTimeRange(row.time)}
        </StyledTableCell>
        <StyledTableCell align="center">
          <Tag color={`${row.status === "正常" ? "green" : "red"}`}>
            {row.status}
          </Tag>
        </StyledTableCell>
        <StyledTableCell align="center">{row.residents}</StyledTableCell>
        <StyledTableCell align="center">{row.guests}</StyledTableCell>
      </StyledTableRow>
      <TableRow>
        <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            <Box sx={{ margin: 1 }}>
              <Table size="small" aria-label="purchases">
                <TableBody>
                  {row.danger?.map((dangerRow: any, index: number) => (
                    <TableRow key={`${index}-${dangerRow.start_time}`}>
                      <DangerTableCell
                        align="center"
                        component="th"
                        scope="row"
                      >
                        {index + 1}
                      </DangerTableCell>
                      <DangerTableCell align="center">
                        {dangerRow.start_time}
                      </DangerTableCell>
                      <DangerTableCell align="center">
                        {dangerRow.action}
                      </DangerTableCell>
                      <DangerTableCell align="center">
                        {dangerRow.remark[1]}
                      </DangerTableCell>
                      <DangerTableCell align="center">
                        {dangerRow.remark[2]}
                      </DangerTableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </Fragment>
  );
}

// @ts-ignore
export const ActivityReport: FC<{ user: SystemUserInfoData }> = ({ user }) => {
  const [value, setValue] = useState<string>("1");
  const [report, setReport] = useState<any>(null);
  const [page, setPage] = useState(0);
  const [rowsPerPage] = useState(10);
  const [emptyRows, setEmptyRows] = useState<number[]>([0]);
  const [dateRange, setDateRange] = useState([
    dayjs().subtract(1, "day").format("YYYY-MM-DD"), // Yesterday
    dayjs().subtract(1, "day").format("YYYY-MM-DD"), // Today
  ]);
  const [refresh, setRefresh] = useState<any>(false);
  const api = useAPI();

  useEffect(() => {
    if (dateRange[0] === undefined) {
      dateRange[0] = dayjs().subtract(1, "day").format("YYYY-MM-DD");
      dateRange[1] = dayjs().subtract(1, "day").format("YYYY-MM-DD");
    }

    api
      .getElderReport(
        user?.userId,
        `${dateRange[0].replace(/[-: ]/g, "_")}_00_00_00`,
        `${dateRange[1].replace(/[-: ]/g, "_")}_23_59_59`,
        "hour"
      )
      .then((response) => {
        const inputData = response.data.data;
        // Step 4: Get the table format
        const tableData = inputData.map((item: any, index: number) => {
          // Check if there is any "摔倒" action
          return createData(
            index + 1,
            item.hour,
            item.status,
            item.remark[1],
            item.remark[2],
            item.event
          );
        });

        const totalPages = Math.ceil(tableData.length / rowsPerPage); // Total number of pages
        let tmp = Array.from({ length: totalPages }).map((_, pageIndex) => {
          const startRow = pageIndex * rowsPerPage;
          // Calculate empty rows for the current page
          const rowsInCurrentPage = Math.min(
            tableData.length - startRow,
            rowsPerPage
          );
          return rowsPerPage - rowsInCurrentPage;
        });

        setReport(tableData);
        setEmptyRows(tmp);
      });
  }, [dateRange, refresh]);

  const handleChangePage = (_event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChange = (_event: SyntheticEvent, newValue: string) => {
    setValue(newValue);
  };

  // @ts-ignore
  return (
    <div>
      <h3
        className={css`
          border-left: 3px solid rgb(var(--primary-6));
          padding-left: 12px;
          border-radius: 2px;
          margin-bottom: 10px;
        `}
      >
        活动报告
      </h3>

      {report ? (
        <Box sx={{ bgcolor: "background.paper" }}>
          <TabContext value={value}>
            <TabList onChange={handleChange} aria-label="icon tabs example">
              <Tab
                value="1"
                label="&bull; 房间概览 &bull;"
                iconPosition="start"
              />
              <Tab
                value="2"
                label="&bull; 活动总结 &bull;"
                iconPosition="start"
              />
              <Tab
                value="3"
                label="&bull; 活动列表 &bull;"
                iconPosition="start"
              />
            </TabList>
            <TabPanel value="1">
              {report ? (
                <>
                  <Form layout="inline">
                    <Form.Item label="查询日期：">
                      <DatePicker
                        onChange={(e) => {
                          setDateRange([e, e]);
                          setRefresh(!refresh);
                        }}
                        disabledDate={disableFutureDates}
                        defaultValue={dateRange[0]}
                      />
                    </Form.Item>
                  </Form>
                  <TableContainer>
                    <Table
                      sx={{ maxHeight: 200 }}
                      size="small"
                      aria-label="custom pagination table"
                    >
                      <TableHead>
                        <TableRow>
                          <StyledTableCell></StyledTableCell>
                          <StyledTableCell align="center" rowSpan={2}>
                            序号
                          </StyledTableCell>
                          <StyledTableCell align="center">时间</StyledTableCell>
                          <StyledTableCell align="center" rowSpan={2}>
                            房间状态
                          </StyledTableCell>
                          <StyledTableCell align="center" colSpan={2}>
                            屋内人员数量（人）
                          </StyledTableCell>
                        </TableRow>
                        <TableRow>
                          <StyledTableCell></StyledTableCell>
                          <StyledTableCell align="center">
                            {dateRange[0]}
                          </StyledTableCell>
                          <StyledTableCell align="center">住户</StyledTableCell>
                          <StyledTableCell align="center">访客</StyledTableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {(rowsPerPage > 0 && report
                          ? report.slice(
                              page * rowsPerPage,
                              page * rowsPerPage + rowsPerPage
                            )
                          : report
                        ).map((row: any, index: number) => (
                          <>
                            <Row key={`${index}-${row.startTime}`} row={row} />
                          </>
                        ))}
                        <TableRow style={{ height: 35 * emptyRows[page] }}>
                          <TableCell colSpan={6} />
                        </TableRow>
                      </TableBody>
                      <TableFooter style={{ marginBottom: "-2px" }}>
                        <TableRow>
                          <TablePagination
                            labelDisplayedRows={({ from, to, count }) =>
                              `第 ${from}–${to} 条，共 ${count} 条`
                            }
                            count={report.length}
                            rowsPerPage={10}
                            rowsPerPageOptions={[10]}
                            page={page}
                            onPageChange={handleChangePage}
                          />
                        </TableRow>
                      </TableFooter>
                    </Table>
                  </TableContainer>
                </>
              ) : null}
            </TabPanel>
            <TabPanel value="2">
              <ActivityChart userId={user?.userId} />
            </TabPanel>
            <TabPanel value="3">
              <ActivityListAndRecord
                userId={user?.userId}
                dateRange={dateRange[0]}
                setDateRange={setDateRange}
              />
            </TabPanel>
          </TabContext>
        </Box>
      ) : (
        <h3
          className={css`
            border-left: 3px solid rgb(var(--primary-6));
            padding-left: 12px;
            border-radius: 2px;
            margin-top: 30px;
          `}
        >
          数据加载中...
        </h3>
      )}
    </div>
  );
};
